package com.weilive.api.gate.servlet;

import org.jboss.netty.handler.codec.http.HttpRequest;
import org.jboss.netty.handler.codec.http.HttpResponse;
import org.jboss.netty.util.CharsetUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.weilive.api.gate.servlet.protocol.black.FromBlackMsg;
import com.weilive.api.gate.servlet.protocol.black.ToBlackMsg;
import com.weilive.api.service.BlackSystem;
import com.weilive.core.netty.http.HttpServlet;

@Service
public class BlackServlet extends HttpServlet {

	@Autowired
	private BlackSystem blackSystem;

	@Override
	public String getServletPath() {
		return "/api/black";
	}

	@Override
	public HttpResponse processRequest(HttpRequest request) throws Exception {
		String data = request.getContent().toString(CharsetUtil.UTF_8);
		ToBlackMsg toMsg = new ToBlackMsg();
		if (data == null || data.equals("")) {
			toMsg.setVersion(blackSystem.getVersion());
			toMsg.setBlack(blackSystem.getBlackList());
			return createJsonResponse(JSONObject.toJSONString(toMsg));
		} else {
			FromBlackMsg fromMsg = (FromBlackMsg) JSONObject.parseObject(data, FromBlackMsg.class);
			if (blackSystem.getVersion().equals(fromMsg.getVersion())) {
				toMsg.setIsSuccessFlag("0");
				return createJsonResponse(JSONObject.toJSONString(toMsg));
			}
			toMsg.setVersion(blackSystem.getVersion());
			toMsg.setBlack(blackSystem.getBlackList());
			return createJsonResponse(JSONObject.toJSONString(toMsg));
		}

	}
}